package com.glowdayz.glowmee;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.PorterDuff;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.ContextThemeWrapper;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RatingBar;
import android.widget.TextView;

import com.glowdayz.common.ActivityManager;
import com.glowdayz.common.CDialog;
import com.glowdayz.common.DateTime;
import com.glowdayz.common.XmlParser;
import com.glowdayz.model.AddItem;
import com.glowdayz.model.ReviewCommentCMD;
import com.glowdayz.model.UserInfo;

public class ReviewProduct extends Activity implements OnScrollListener, OnClickListener {
	
	private ActivityManager am = ActivityManager.getInstance();
	
	ListView listReview = null;
	ArrayList<ReviewCommentCMD> list = null;
	DataAdapter adapter = null;
	
	ImageView ratingImg1 = null, ratingImg2 = null, ratingImg3 = null, ratingImg4 = null, ratingImg5 = null;
	
	// Footer 레이아웃
	LinearLayout llFooter = null;
	LinearLayout llHeader = null;
	
	/********** 페이지 구현 **********/
	private int page = 1;						// 현재 페이지
	private final static int pageSize = 20;		// 한 페이지에 보일 수
	private int totalCount = 0;					// 전체 게시물 수
	
	double PARAM_rating = 0.0;
    int PARAM_id = 0, PARAM_ratingCount = 0, PARAM_rating1 = 0, PARAM_rating2 = 0, PARAM_rating3 = 0, PARAM_rating4 = 0, PARAM_rating5 = 0;
    String PARAM_productTitle = null, PARAM_brandTitle= null;
    
    int paramFilter = 0, paramOrder = 0, paramRating = 0, paramAge = 0, paramSkin = 0;
	int paramIdProduct = 0;
	
	int intRating = 0;
	
	LinearLayout noReviewLayout = null;
    
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_review_product);
		
		am.addActivity(this);
		
		Intent fromIntent = getIntent();
		PARAM_id = fromIntent.getIntExtra("PARAM_id", 0);
		PARAM_rating = fromIntent.getDoubleExtra("PARAM_rating", PARAM_rating);
		PARAM_ratingCount = fromIntent.getIntExtra("PARAM_ratingCount", 0);
		PARAM_rating1 = fromIntent.getIntExtra("PARAM_rating1", 0);
		PARAM_rating2 = fromIntent.getIntExtra("PARAM_rating2", 0);
		PARAM_rating3 = fromIntent.getIntExtra("PARAM_rating3", 0);
		PARAM_rating4 = fromIntent.getIntExtra("PARAM_rating4", 0);
		PARAM_rating5 = fromIntent.getIntExtra("PARAM_rating5", 0);
		PARAM_productTitle = fromIntent.getStringExtra("PARAM_productTitle");
		PARAM_brandTitle = fromIntent.getStringExtra("PARAM_brandTitle");
		
		if (PARAM_id > 0) {
			paramIdProduct = PARAM_id;
		}
		
		ImageView backBt = (ImageView) findViewById(R.id.backBt);
		backBt.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN: {
                        ImageView view = (ImageView) v;
                        view.getDrawable().setColorFilter(0x77000000,PorterDuff.Mode.SRC_ATOP);
                        view.invalidate();
                        break;
                    }
                    case MotionEvent.ACTION_UP:
                    case MotionEvent.ACTION_CANCEL: {
                        ImageView view = (ImageView) v;
                        view.getDrawable().clearColorFilter();
                        view.invalidate();
                        break;
                    }
                }
                return false;
            }
        });
		backBt.setOnClickListener(new Button.OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		
		ImageView okBt = (ImageView) findViewById(R.id.okBt);
		okBt.setImageResource(R.drawable.pick_search);
		okBt.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN: {
                        ImageView view = (ImageView) v;
                        view.getDrawable().setColorFilter(0x77000000,PorterDuff.Mode.SRC_ATOP);
                        view.invalidate();
                        break;
                    }
                    case MotionEvent.ACTION_UP:
                    case MotionEvent.ACTION_CANCEL: {
                        ImageView view = (ImageView) v;
                        view.getDrawable().clearColorFilter();
                        view.invalidate();
                        break;
                    }
                }
                return false;
            }
        });
		okBt.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(ReviewProduct.this, ReviewProductFilter.class);
				intent.putExtra("PARAM_idProduct", paramIdProduct);
				intent.putExtra("PARAM_order", paramOrder);
				intent.putExtra("PARAM_rating", paramRating);
				intent.putExtra("PARAM_age", paramAge);
				intent.putExtra("PARAM_skin", paramSkin);
				startActivityForResult(intent, 2);
			}
		});
		
		TextView textTitle = (TextView) findViewById(R.id.textTitle);
		textTitle.setText("사용자리뷰");
		
		listReview = (ListView) findViewById(R.id.listReview);
		LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		llHeader = (LinearLayout) inflater.inflate(R.layout.inc_review_header, null);
		listReview.addHeaderView(llHeader);
		
		ratingImg1 = (ImageView) llHeader.findViewById(R.id.ratingImg1);
		ratingImg2 = (ImageView) llHeader.findViewById(R.id.ratingImg2);
		ratingImg3 = (ImageView) llHeader.findViewById(R.id.ratingImg3);
		ratingImg4 = (ImageView) llHeader.findViewById(R.id.ratingImg4);
		ratingImg5 = (ImageView) llHeader.findViewById(R.id.ratingImg5);
		ratingImg1.setOnClickListener(this);
		ratingImg2.setOnClickListener(this);
		ratingImg3.setOnClickListener(this);
		ratingImg4.setOnClickListener(this);
		ratingImg5.setOnClickListener(this);
		
		RatingBar ratingBar = (RatingBar) llHeader.findViewById(R.id.ratingBar);
		TextView ratingAvg = (TextView) llHeader.findViewById(R.id.ratingAvg);
		TextView ratingCount = (TextView) llHeader.findViewById(R.id.ratingCount);
		TextView ratingText1 = (TextView) llHeader.findViewById(R.id.ratingText1);
		TextView ratingText2 = (TextView) llHeader.findViewById(R.id.ratingText2);
		TextView ratingText3 = (TextView) llHeader.findViewById(R.id.ratingText3);
		TextView ratingText4 = (TextView) llHeader.findViewById(R.id.ratingText4);
		TextView ratingText5 = (TextView) llHeader.findViewById(R.id.ratingText5);
		
		noReviewLayout = (LinearLayout) llHeader.findViewById(R.id.noReviewLayout);
		
		ratingAvg.setText(String.valueOf(PARAM_rating));
		ratingCount.setText(PARAM_ratingCount + " reviews");
		ratingText1.setText(String.valueOf(PARAM_rating1));
		ratingText2.setText(String.valueOf(PARAM_rating2));
		ratingText3.setText(String.valueOf(PARAM_rating3));
		ratingText4.setText(String.valueOf(PARAM_rating4));
		ratingText5.setText(String.valueOf(PARAM_rating5));
		
		ratingBar.setOnTouchListener(new OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				return true;
			}
		});
		ratingBar.setStepSize((float) 0.1);
		ratingBar.setRating(Float.parseFloat(String.valueOf(PARAM_rating)));
		
		TextView blogReviewBt = (TextView) llHeader.findViewById(R.id.blogReviewBt);
		ImageView addReviewBt = (ImageView) llHeader.findViewById(R.id.addReviewBt);
		blogReviewBt.setOnClickListener(this);
		addReviewBt.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN: {
                        ImageView view = (ImageView) v;
                        view.getDrawable().setColorFilter(0x77000000,PorterDuff.Mode.SRC_ATOP);
                        view.invalidate();
                        break;
                    }
                    case MotionEvent.ACTION_UP:
                    case MotionEvent.ACTION_CANCEL: {
                        ImageView view = (ImageView) v;
                        view.getDrawable().clearColorFilter();
                        view.invalidate();
                        break;
                    }
                }
                return false;
            }
        });
		addReviewBt.setOnClickListener(this);
		
		// 메인 디지안과 별도로 레이아웃을 불러오기
		LayoutInflater li = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		llFooter = (LinearLayout) li.inflate(R.layout.list_footer, null);
		llFooter.setVisibility(View.GONE);
		// 리스트뷰에 추가
		listReview.addFooterView(llFooter);
		listReview.setOnScrollListener(this);
		
		list = new ArrayList<ReviewCommentCMD>();
		adapter = new DataAdapter(this, list);
		listReview.setAdapter(adapter);
		
		(new ReviewWorker()).execute();
	}
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.blogReviewBt:
			Intent intent = new Intent(this, WebPage.class);
			intent.putExtra("PARAM_bannerUrl", "http://m.blog.naver.com/SectionPostSearch.nhn?searchValue=" + 
			PARAM_brandTitle + " " + PARAM_productTitle);
			startActivity(intent);
			break;
		case R.id.addReviewBt:
			if (UserInfo.getInstance().getUSER_ID() == 0) {
				AlertDialog.Builder confirm = new AlertDialog.Builder(new ContextThemeWrapper(this, android.R.style.Theme_Holo_Light_Dialog));
				confirm.setTitle("로그인 안내");
				confirm.setMessage("로그인 이후에 서비스 이용이 가능합니다.");
				confirm.setCancelable(false);
				confirm.setPositiveButton("확인", new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						Intent intent = new Intent(ReviewProduct.this, Login.class);
						intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
						startActivity(intent);
						return;
					}
				});
				confirm.create();
				confirm.show();
			} else {
				intRating = 0;
				(new CheckWorker()).execute();
			}
			break;
		case R.id.ratingImg1:
			goReviewProduct(1);
			break;
		case R.id.ratingImg2:
			goReviewProduct(2);
			break;
		case R.id.ratingImg3:
			goReviewProduct(3);
			break;
		case R.id.ratingImg4:
			goReviewProduct(4);
			break;
		case R.id.ratingImg5:
			goReviewProduct(5);
			break;
		}
		
	}
	
	public void goReviewProduct(int rating) {
		if (UserInfo.getInstance().getUSER_ID() == 0) {
			AlertDialog.Builder confirm = new AlertDialog.Builder(new ContextThemeWrapper(this, android.R.style.Theme_Holo_Light_Dialog));
			confirm.setTitle("로그인 안내");
			confirm.setMessage("로그인 이후에 서비스 이용이 가능합니다.");
			confirm.setCancelable(false);
			confirm.setPositiveButton("확인", new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					Intent intent = new Intent(ReviewProduct.this, Login.class);
					intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
					startActivity(intent);
					return;
				}
			});
			confirm.create();
			confirm.show();
		} else {
			intRating = rating;
			(new CheckWorker()).execute();
		}
	}
	
	public class CheckWorker extends AsyncTask<Object, AddItem, Object> {
		@Override
		protected void onPreExecute() {
			CDialog.showLoading(ReviewProduct.this);
		}

		@Override
		protected Object doInBackground(Object... params) {
			Object result = null;
			
			String url = getResources().getString(R.string.server_url) + "/glowmee/addReviewProductXml.do?idRegister=" + UserInfo.getInstance().getUSER_ID()
					+ "&idProduct=" + PARAM_id + "&check=1";
			
			XmlPullParser parser = XmlParser.getInstance().getParser(url);
			// 통신 실패시 예외처리
			if (parser == null) {
				this.cancel(true);
				return null;
			}
			
			try {
				String tag = null;
				int type = parser.getEventType();
				
				/** 읽은 내용을 담기 위한 변수 */
				String rt = null;
				String rtmsg = null;
				int seq = 0;
				// 파싱 처리를 위한 반복 시작
				while (type != XmlPullParser.END_DOCUMENT) {
					// 읽은 태그의 이름
					tag = parser.getName();

					// 현재 읽고 있는 태그의 종류별로 분기
					switch (type) {
					case XmlPullParser.START_TAG:
						/** 원하는 종류의 시작태그를 만났을 때, 값을 추출 */
						if (tag.equals("rt")) {
							parser.next();
							rt = parser.getText();
						} else if (tag.equals("rtmsg")) {
							parser.next();
							rtmsg = parser.getText();
						} else if (tag.equals("seq")) {
							parser.next();
							seq = Integer.parseInt(parser.getText().trim());
						}
						
						break;

					case XmlPullParser.END_TAG:
						
						if (tag.equals("JSPglowmee")) {
							AddItem item = new AddItem(rt, rtmsg, seq);
							publishProgress(item);
						}
						break;
					}

					// 다음 태그로 이동하고, 상태값을 변경
					type = parser.next();
				}

			} catch (XmlPullParserException e) {
				System.out.println("파서 생성 실패 >> " + e.toString());
			} catch (IOException e) {
				System.out.println("파서 읽기 실패 >> " + e.toString());
			}
			
			return result;
		}

		@Override
		protected void onProgressUpdate(AddItem... param) {
			if (param[0].getRt().equals("SUCCESS")) {
				Intent intent = new Intent(ReviewProduct.this, AddReviewProduct.class);
				intent.putExtra("PARAM_id", PARAM_id);
				intent.putExtra("PARAM_rating", intRating);
				startActivityForResult(intent, 1);
			} else {
				AlertDialog.Builder alert = new AlertDialog.Builder(new ContextThemeWrapper(ReviewProduct.this, android.R.style.Theme_Holo_Light_Dialog));
				alert.setTitle("등록 실패");
				alert.setMessage(param[0].getRtmsg());
				alert.setCancelable(false);
				alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
					}
				});
				alert.create();
				alert.show();
			}
			
		}

		@Override
		protected void onPostExecute(Object param) {
			CDialog.hideLoading();
		}

		@Override
		protected void onCancelled() {
			CDialog.hideLoading();
			AlertDialog.Builder alert = new AlertDialog.Builder(new ContextThemeWrapper(ReviewProduct.this, android.R.style.Theme_Holo_Light_Dialog));
			alert.setMessage("일시적인 통신에러입니다.");
			alert.setCancelable(false);
			alert.setPositiveButton("다시 시도", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					(new CheckWorker()).execute();
				}
			});
			alert.setNegativeButton("뒤로 가기", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					finish();
				}
			});
			alert.create();
			alert.show();
		}
	}
	
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == Activity.RESULT_OK) {
			if (requestCode == 1) {
				Intent intent = new Intent();
				setResult(Activity.RESULT_OK, intent);
				finish();
			} else if (requestCode == 2) {
				paramFilter = data.getIntExtra("PARAM_filter", 0);
				paramOrder = data.getIntExtra("PARAM_order", 0);
				paramRating = data.getIntExtra("PARAM_rating", 0);
				paramAge = data.getIntExtra("PARAM_age", 0);
				paramSkin = data.getIntExtra("PARAM_skin", 0);
				paramIdProduct = data.getIntExtra("PARAM_idProduct", 0);
				
				adapter.clear();
				(new ReviewWorker()).execute();
			}
			
		}
	}
	
	public class DataAdapter extends ArrayAdapter<ReviewCommentCMD> {
		private LayoutInflater inflater = null;

		// 생성자. 파라미터에 전달되는 List의 제너릭스 선언에 주의한다.
		public DataAdapter(Context context, List<ReviewCommentCMD> objects) {
			super(context, 0, objects);
			inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		}

		// ArrayList에 할당된 각 항목을 하나씩 추출하여 list_item.xml에 표현시키는 메서드
		// 이 메서드는 ListView에 의해서 호출된다.
		@SuppressLint("SimpleDateFormat")
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			/** 모든 컴포넌트의 최상위 클래스 */
			View view = null;

			// 데이터를 저장할 View 선언. view 객체는 "list_item.xml"파일을 의미한다.
			if (convertView == null) {
				view = inflater.inflate(R.layout.list_review_item, null);
			} else {
				view = convertView;
			}

			// 하나의 데이터 항목을 추출한다.
			ReviewCommentCMD item = getItem(position);

			// 추출한 데이터가 존재한다면 "list_item.xml"안의 컨트롤들을 추출하여 처리한다.
			if (item != null) {
				LinearLayout commentLayout = (LinearLayout) view.findViewById(R.id.commentLayout);
				commentLayout.setBackgroundResource(R.drawable.box_review);
				
				ImageView userImg = (ImageView) view.findViewById(R.id.userImg);
				ImageView ratingImg = (ImageView) view.findViewById(R.id.ratingImg);
				
				TextView reviewText = (TextView) view.findViewById(R.id.reviewText);
				TextView userInfo = (TextView) view.findViewById(R.id.userInfo);
				TextView create_date = (TextView) view.findViewById(R.id.create_date);
				
				reviewText.setText(item.getReviewText());
				
				switch (item.getRating()) {
				case 1:
					ratingImg.setImageResource(R.drawable.rating1);
					break;
				case 2:
					ratingImg.setImageResource(R.drawable.rating2);
					break;
				case 3:
					ratingImg.setImageResource(R.drawable.rating3);
					break;
				case 4:
					ratingImg.setImageResource(R.drawable.rating4);
					break;
				case 5:
					ratingImg.setImageResource(R.drawable.rating5);
					break;
				}
				
				if (item.getSkinType().equals("null") && item.getBirthYear() != 0) {
					int age = Calendar.getInstance().get(Calendar.YEAR) - item.getBirthYear() + 1;
					userInfo.setText(item.getIdRegisterValue() + "(" + age + "세" + ")");
				} else if (!item.getSkinType().equals("null") && item.getBirthYear() == 0) {
					userInfo.setText(item.getIdRegisterValue() + "(" + item.getSkinType() + ")");
				} else if (!item.getSkinType().equals("null") && item.getBirthYear() != 0) {
					int age = Calendar.getInstance().get(Calendar.YEAR) - item.getBirthYear() + 1;
					userInfo.setText(item.getIdRegisterValue() + "(" + age + "세/" + item.getSkinType() + ")");
				} else if (item.getSkinType().equals("null") && item.getBirthYear() == 0) {
					userInfo.setText(item.getIdRegisterValue());
				}
				
				try {
					Date date = (new SimpleDateFormat("yyyyMMddHHmmss")).parse(item.getCreate_date().trim());
					String time = DateTime.getInstance().calculateTime(date);
					if (time == null) {
						create_date.setText(DateTime.getInstance().getDateTimeString3(item.getCreate_date().trim()));
					} else {
						create_date.setText(time);
					}
				} catch (ParseException e) {
					e.printStackTrace();
				}
				
				if (item.getBm() == null) {
					userImg.setImageResource(R.drawable.profileimg);
				} else {
					userImg.setImageBitmap(item.getBm());
				}
				
			}
			return view;
		}
	}
	
	public class ReviewWorker extends AsyncTask<Object, ReviewCommentCMD, Object> {
		@Override
		protected void onPreExecute() {
			CDialog.showLoading(ReviewProduct.this);
		}

		@Override
		protected Object doInBackground(Object... params) {
			Object result = null;
			
			String url = null;
			
			switch (paramFilter) {
			case 0:
				url = getResources().getString(R.string.server_url) + "/glowmee/reviewProductXml.do?" +
						"page=" + page + "&count=" + pageSize + "&idProduct=" + PARAM_id;
				break;
			case 1:
				url = getResources().getString(R.string.server_url) + "/glowmee/reviewProductXml.do?" +
						"page=" + page + "&count=" + pageSize + "&idProduct=" + paramIdProduct +
						"&order=" + paramOrder + "&rating=" + paramRating + "&age=" + paramAge + "&skin=" + paramSkin;
				break;
			}
			
			XmlPullParser parser = XmlParser.getInstance().getParser(url);
			if (parser == null) {
				this.cancel(true);
				return null;
			}
			
			try {
				String tag = null;
				int type = parser.getEventType();

				/** 읽은 내용을 담기 위한 변수 */
				int idRegister = 0;
				String idRegisterValue = null;
				int birthYear = 0;
				String skinType = null;
				int rating = 0;
				String reviewText = null;
				String create_date = null;
				String thumbnail = null;
				String userImg = null;
				
				// 파싱 처리를 위한 반복 시작
				while (type != XmlPullParser.END_DOCUMENT) {
					// 읽은 태그의 이름
					tag = parser.getName();

					// 현재 읽고 있는 태그의 종류별로 분기
					switch (type) {
					case XmlPullParser.START_TAG:
						/** 원하는 종류의 시작태그를 만났을 때, 값을 추출 */
						if (tag.equals("totalArticleCount")) {
							parser.next();
							totalCount = Integer.parseInt(parser.getText().trim());
						} else if (tag.equals("idRegister")) {
							parser.next();
							idRegister = Integer.parseInt(parser.getText().trim());
						} else if (tag.equals("idRegisterValue")) {
							parser.next();
							idRegisterValue = parser.getText();
						} else if (tag.equals("birthYear")) {
							parser.next();
							birthYear = Integer.parseInt(parser.getText().trim());
						} else if (tag.equals("skinType")) {
							parser.next();
							skinType = parser.getText();
						} else if (tag.equals("rating")) {
							parser.next();
							rating = Integer.parseInt(parser.getText().trim());
						} else if (tag.equals("reviewText")) {
							parser.next();
							reviewText = parser.getText();
						} else if (tag.equals("create_date")) {
							parser.next();
							create_date = parser.getText();
						} else if (tag.equals("thumbnail")) {
							parser.next();
							thumbnail = parser.getText();
						} else if (tag.equals("user_thumbnail")) {
							parser.next();
							userImg = parser.getText();
						}
						
						break;

					case XmlPullParser.END_TAG:
						
						if (tag.equals("item")) {
							Bitmap bm = null;
							if (userImg != null && !userImg.equals("null")) {
								try {
									URL url2 = new URL(getResources().getString(R.string.server_url) + userImg.trim()); 
									URLConnection conn = url2.openConnection(); 
									conn.connect(); 
									BufferedInputStream bis = new BufferedInputStream(conn.getInputStream()); 
									bm = BitmapFactory.decodeStream(bis); 
									bis.close();
								} catch (IOException e) {
									e.printStackTrace();
								}
							}
							
							ReviewCommentCMD item = new ReviewCommentCMD(
									idRegister, idRegisterValue, reviewText, rating, create_date, birthYear, skinType, thumbnail, bm);
							
							publishProgress(item);
						}
						break;
					}

					// 다음 태그로 이동하고, 상태값을 변경
					type = parser.next();
				}

			} catch (XmlPullParserException e) {
				System.out.println("파서 생성 실패 >> " + e.toString());
			} catch (IOException e) {
				System.out.println("파서 읽기 실패 >> " + e.toString());
			}
			
			return result;
		}

		@Override
		protected void onProgressUpdate(ReviewCommentCMD... param) {
			adapter.add(param[0]);
		}

		@Override
		protected void onPostExecute(Object param) {
			if (totalCount == 0) {
				noReviewLayout.setVisibility(View.VISIBLE);
				listReview.setDividerHeight(0);
			}
			CDialog.hideLoading();
		}
		
		@Override
		protected void onCancelled() {
			CDialog.hideLoading();
			AlertDialog.Builder alert = new AlertDialog.Builder(new ContextThemeWrapper(ReviewProduct.this, android.R.style.Theme_Holo_Light_Dialog));
			alert.setMessage("일시적인 통신에러입니다.");
			alert.setCancelable(false);
			alert.setPositiveButton("다시 시도", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					(new ReviewWorker()).execute();
				}
			});
			alert.setNegativeButton("뒤로 가기", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					finish();
				}
			});
			alert.create();
			alert.show();
		}
	}
	
	// 화면에 리스트의 마지막 아이템이 보여지는 체크
	boolean lastItemVisibleFlag = false;
	
	@Override
	public void onScroll(AbsListView view, int firstVisibleItem,
			int visibleItemCount, int totalItemCount) {
		lastItemVisibleFlag = (totalItemCount > 0) && (firstVisibleItem + visibleItemCount >= totalItemCount);
	}

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
		if (scrollState == OnScrollListener.SCROLL_STATE_IDLE && lastItemVisibleFlag) {
			int pageCount = ((totalCount -1) / pageSize) + 1;
			if (pageCount > 0 && page < pageCount) {
				page++;
				(new ReviewWorker()).execute();
			}
		}
	}
	
    @Override
	protected void onDestroy() {
		super.onDestroy();
		am.removeActivity(this);
	}

}
